package com.xxy.interceptors;

import com.xxy.common.Result;
import com.xxy.utils.JwtUtil;
import com.xxy.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * 拦截器
 * @Author xingyu Xue
 * @Date 2024/2/3 14:01
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        //验证token
        try {
            //能解析出token说明就是登录过来，因为这个token就是登录时生成的。
            Map<String, Object> claims = JwtUtil.parseToken(token);
            //把业务数据存储到threadlocal中
            ThreadLocalUtil.set(claims);
//            ThreadLocalUtil.set("hello");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(401);
            return false;
        }


    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }
}
